#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 crane <crane@crane-pc>
#
# Distributed under terms of the MIT license.

"""
    解决kolakoski数列问题

    输出: baseList, maxLen of outputList
"""

class NextNum:
    def __init__(self, baseList):
        self.baseList = baseList
        self.idx = 0
        self.baseLen = len(baseList)

    def next(self):
        tmp = self.baseList[self.idx]
        self.idx = (self.idx + 1) % self.baseLen
        return tmp

def kolakoski(baseList, maxLen):
    nextNum = NextNum(baseList)
    outputList = [None] * maxLen

    outputList[0] = baseList[0]

    cntIdx = 0
    putIdx = 0

    while cntIdx < maxLen and putIdx < maxLen:

        value = nextNum.next()

        cnt = outputList[cntIdx]
        if cnt is None:     # 应付 baseList[0] == 1的情况. 此时baseList[1] = None
            cnt = value

        cntIdx += 1


        while cnt > 0:
            cnt -= 1
            outputList[putIdx] = value
            putIdx += 1

    showList(outputList)



def showList(inlist):
    for num in inlist:
        print(' %s ' % num)



if __name__ == "__main__":
    # baseList = [1, 2]
    baseList = [2, 1, 3, 1]     # 输入数列, 随意
    maxLen = 20                 # 结果数列长度, 这里长度随意

    kolakoski(baseList, maxLen)
